<template>
	<div class="kugou-content">
		<div class="luckyData" v-if="luckyData != ''">
		<!-- banner图 -->
		<img v-if="backgroundImg==''" src="../../static/images/background.png" alt class="bg-banner" />
		<img v-else-if="backgroundImg!=''" :src="backgroundImg" alt class="bg-banner" />
		<!-- 我的奖品 -->
		<img :src="myPrizeButtonImg" class="nav left" @click="myPrize" />
		<!-- 活动规则 -->
		<img :src="ruleButtonImg" class="nav right" @click="showRule" />
		<!-- 滚动号码 -->
		<div class="kugou-scroll">
			<ul class="bg-scroll">
				<img src="../../static/images/winPriceLabel.png" alt class="notice-img" />
				<li v-for="(item, i) in list" :key="i" ref="rollLi" :class="{ 'anim' : animate && i == 0 }">
					<span class="lkq-name">{{ item.phone }}</span>
				</li>
			</ul>
		</div>
		<!-- 抽奖机会 -->
		<div class="opportunity">
			您还有<span>{{frequency}}</span>次抽奖机会
		</div>
		<div class="turntable">
			<div class="present-content" :style="{backgroundImage:`url(${squaredImg})`}">
				<div class="present">
					<div class="present-item" v-for="(item,index) in awards" :class="[{
              'in-column-center': addColumnClass(index + 1),
              'in-row-center': addRowClass(index + 1),
              'current': index == current,
              'middle': item.id == 0
            }]">
						<img class="prize" :src="item.image_url" v-if="index!==4" />
						<div class="present-item-name">{{item.name}}</div>
					</div>
				</div>
			</div>
			<img @click="handleStart" :src=getAwardImg alt class="start-btn-big" v-if="draw" />
			<img src="../../static/images/unableGetAward.png" alt class="disable-start-btn-big" v-else />
			<div class='paticipate-people'>已有{{virtualPeople}}人参与活动</div>
			<!-- <img :src=shareButtonImg alt class="call-friend" @click='showMask = true' /> -->
			
		</div>
		<u-mask :show="show" @click="show = false" z-index="1"></u-mask>
		<u-modal v-model="activityLabel" :title-style="{color: 'black'}" :title=activityTitle :show-title="true" confirm-text="我知道了">
			<view class="slot-content" style="padding: 15rpx 15rpx;overflow:hidden;">
				<rich-text :nodes="activityDesc"></rich-text>
			</view>
		</u-modal>
		<u-modal v-model="showRuleLabel" :title-style="{color: 'black'}" title=活动规则 :show-title="true">
			<view class="slot-content" style="padding: 15rpx 15rpx;overflow:hidden;">
				<rich-text :nodes="ruleContent"></rich-text>
			</view>
		</u-modal>
		<u-modal v-model="showFollow" :confirm-style="{color: '#2979ff', 'background-color':'#fff'}" :show-title="true" title="关注后才能参与活动">
			<image style="width: 100%" :src="followQrcode" />
		</u-modal>
		<u-modal @confirm="goToVerify" v-model="showVerify" :confirm-style="{color: '#2979ff', 'background-color':'#fff'}"
		 confirm-text="立即认证" :show-title="true" title="实名身份认证">
			<view class="slot-content" style="padding: 15rpx 15rpx;overflow:hidden;">
				<text>{{verifyContent}}</text>
			</view>
		</u-modal>
		<notRegisterPop :show.sync="show" @register="register" v-if="false"></notRegisterPop>
		<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
		<NotWinOne :show.sync="show" v-if="false"></NotWinOne>
		<NotWinThree :show.sync="show" v-if="false"></NotWinThree>
		<Win :show.sync="show" @getItNow="getItNow" :msgBgImg='msgBgImg' :activityId=activityId v-if="true" :prizeTitle='prizeTitle' :prizeImg='prizeImg'
		 :prizeType='prizeType'></Win>
		<u-mask :show="showMask" @click="showMask = false">
			<image style="width: 90%;left: 50rpx;" src="../../static/images/shareGuid.png"></image>
		</u-mask>
		</div>
	</div>
</template>
<script>
	import notRegisterPop from '../../components/notRegister/NotRegisterPop.vue'
	import NotWinOne from '../../components/notWin/NotWinOne.vue'
	import NotWinTow from '../../components/notWin/NotWinTow.vue'
	import NotWinThree from '../../components/notWin/NotWinThree.vue'
	import Win from '../../components/win/Win.vue'
	import Vue from 'vue';
	import awardsData from '../../common/awards.js'
	import {
		uploadPageInfo,
	} from '@/util/collection.js';


	export default {
		name: "luckyDraw",
		components: {
			notRegisterPop,
			NotWinOne,
			NotWinTow,
			NotWinThree,
			Win
		},
		data() {
			return {
				endAt: '',
				title: '',
				addressHeadImg: '',
				myPrizeButtonImg: 'static/images/myprice.png',
				ruleButtonImg: 'static/images/rule.png',
				msgBgImg: '',
				shareButtonImg: 'static/images/callFriends.png',
				getAwardImg: 'static/images/getAward.png',
				myPrizeBg: '',
				backButtonImg: '',
				receiveImg: '',
				activityDesc: '',
				activityTitle: '',
				verifyUrl: "",
				followQrcode: '',
				showMask: false,
				verifyContent: '为了响应国家号召，需进行实名身份验证，完成身份验证的用户可获得3次抽奖机会',
				codeTips: '',
				showVerify: false,
				showFollow: false,
				activityId: 0,
				virtualPeople: 0,
				showRuleLabel: false,
				backgroundImg: '',
				squaredImg: '',
				draw: true,
				show: false,
				frequency: 0,
				animate: false,
				initSpeed: 200, // 初始速度
				speed: null, // 变化速度
				diff: 20, // 速度变化的值，值越大，变化地越快
				award: {}, // 抽中的奖品
				awards: [],
				time: 0, // 记录开始抽奖的时间
				current: 0, // 当前转动的位置
				isRuningLucky: false, // 是否正在抽奖
				list: [ // 中奖号码
					{
						phone: "186****2336抽中0元话费"
					},
					{
						phone: "166****2336抽中1元话费"
					},
					{
						phone: "156****2336抽中2元话费"
					}
				],
				//旋转规则
				rule: [0, 1, 2, 5, 8, 7, 6, 3],
				ruleContent: '',
				prizeTitle: "奖品名称",
				prizeImg: "../../static/images/prize_1.png",
				prizeType: 0,
				labelPosition: 'left',
				border: false,
				activityLabel: false,
				parent_id: 0,
				activityInfo: {},
				rNUm: 0,
				luckyData:''
			}
		},
		created() {
			
		

		},
		onLoad(options) {
			console.log('onLoad---->', options);
			this.activityId = options.id
			this.parent_id = options.parent_id
			console.log('--->parent_id-->', this.parent_id)
			
			this.setParnet()
			this.iniGetInfo();
			

		},
		onShow(){
			uploadPageInfo(this.activityId,this.$api.collection.saveAddonsInfo,'pages/luckyDraw/luckyDraw');
		},
		mounted() {
			let scrollTimer = setInterval(this.scroll, 2000);
		},
		methods: {
			goToVerify() {
				window.location.href = this.verifyUrl;
			},
			iniGetInfo() {
				let that = this;
				this.$request({
					url: that.$api.luckyDraw.getActivityData,
					method: 'get',
					data: {
						activityid: that.activityId
					},
				}).then(info => {
					console.log(info);
					if (info.code == 203) {
						uni.showToast({
							title: info.msg,
							icon: 'none',
							duration:3000
						})
						return false;
					}
					that.luckyData = info;
					var result = info.data;
					that.initAwards(result.activityInfo.gifts);
					that.ruleContent = result.activityInfo.rule;
					that.backgroundImg = result.activityInfo.activityTemplate.bgimg;
					that.squaredImg = result.activityInfo.activityTemplate.thumb;
					that.activityInfo = result.activityInfo;
					that.list = result.virtualFans;
					that.receiveImg = result.activityInfo.receive_img;
					that.backButtonImg = result.activityInfo.back_button_img;
					that.myPrizeBg = result.activityInfo.my_prize_bg;
					that.getAwardImg = result.activityInfo.now_button_img;
					that.shareButtonImg = result.activityInfo.share_button_img;
					that.ruleButtonImg = result.activityInfo.rule_img;
					that.myPrizeButtonImg = result.activityInfo.my_prize_button;
					that.msgBgImg = result.activityInfo.win_bg;
					that.addressHeadImg = result.activityInfo.receive_img;
					that.frequency = result.canLotteryNum;
					that.virtualPeople = result.activityInfo.virtual_num;
					that.title = result.activityInfo.name;
					that.endAt = result.activityInfo.end_at;
					document.querySelector("html").style.backgroundColor = result.activityInfo.activityTemplate.color;
					document.querySelector(".kugou-content").style.backgroundColor = result.activityInfo.activityTemplate.color;
					uni.setNavigationBarTitle({
						    title: result.activityInfo.name
						});
					//设置分享
					that.initShare();

					//活动数据存入缓存
					uni.setStorage({
						key: 'taibao_luckyDraw_data' + that.activityId,
						data: {
							activityId: that.activityId,
							ruleContent: that.ruleContent,
							backgroundImg: that.backgroundImg,
							ruleButtonImg: that.ruleButtonImg,
							myPrizeBg: that.myPrizeBg,
							backButtonImg: that.backButtonImg,
							addressHeadImg: that.addressHeadImg,
							title: that.title,
							endAt: that.endAt
						},
						success: function() {
							console.log('success');
						}
					});


				}).catch(error => {
					console.log(error)
				})
			},
			codeChange(text) {
				this.codeTips = text;
			},

			showRule() {
				this.showRuleLabel = true;
			},
			setParnet() {
				console.log('parent_id', this.parent_id, this.activityId)
				if (!this.parent_id) {
					return;
				}
				this.$request({
					url: this.$api.user.parent,
					method: 'get',
					data: {
						activity_id: this.activityId,
						parent_id: this.parent_id,
					},
				}).then(info => {

				}).catch(error => {
					console.log(error)
				})
			},
			initShare() {
				let _this = this;
				
				this.$jwx.initJssdk(function(res,jweixin) {
					console.log('wxjscong-->',res)
				    jweixin.ready(function() {  
				        jweixin.updateAppMessageShareData({
							title: _this.activityInfo.share_title || 'title', // 分享标题
							desc: _this.activityInfo.share_desc || 'desc', // 分享描述
							link: _this.activityInfo.share_url || 'link', // 分享链接
							imgUrl: _this.activityInfo.share_friend_img || 'title', // 分享图标
							success: function (res) {
								console.log('//分享成功', res)
								// _this.shareSuccess();
							}
				        });
						
						jweixin.updateTimelineShareData({
						    title: _this.activityInfo.share_title || 'titl', // 分享标题
						    link:  _this.activityInfo.share_url || 'link', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
						    imgUrl: _this.activityInfo.share_friend_img || 'link', // 分享图标
						    success: function () {
						      //分享成功
						      console.log('//分享成功', res)
						      // _this.shareSuccess();
						    }
						 })
				    });  
				});  
			},
			shareSuccess() {
				this.$request({
					url: this.$api.user.share,
					method: 'get',
					data: {
						activity_id: this.activityId
					},
				}).then(info => {

				}).catch(error => {
					console.log(error)
				})
			},
			// 抽奖
			handleStart() {
				if (this.isRuningLucky) {
					uni.showToast({
						title: "正在抽奖中...",
						icon: 'none'
					})
					return false;
				}
				if (isNaN(Number(this.initSpeed))) {
					return false;
				}
				this.speed = this.initSpeed;
				
				
				// 清空上次中奖记录
				this.award = {};
				
				this.isRuningLucky = true;
				this.time = Date.now();
				this.drawAward();
			},
			showPopup(name, image_url, type) {
				this.show = true;
				this.prizeTitle = name;
				this.prizeImg = image_url;
				this.prizeType = type;
			},
			drawAward() {
				console.log('drawaward');
				var that = this;
				
				this.$request({
					url: that.$api.luckyDraw.playGame,
					method: 'get',
					data: {
						activityid: that.activityId
					},
				}).then(info => {
					console.log(info);

					if (info.code == 203) {
						uni.showToast({
							title: info.msg,
							icon: 'none',
							duration:3000
						})
						this.isRuningLucky = false;
						return false;
					} else if (info.code == 204) {
						//未关注
						this.isRuningLucky = false;
						this.followQrcode = info.data.url;
						this.showFollow = true;
						return false;
					} else if (info.code == 206) {
						//活动未实名认证
						this.isRuningLucky = false;
						this.showVerify = true;
						this.verifyUrl = info.data.url;
						return false;
					} else if (info.code == 207 || info.code == 208) {
						//活动未开始或已结束
						this.isRuningLucky = false;
						this.activityLabel = true;
						this.activityDesc = info.data.title;
						this.activityTitle = info.data.desc;
						return false;
					}

					if (info.code == 200 && info.data.key) {
						uni.showToast({
							title: "开始抽奖",
							icon: 'none',
							duration:3000
						})
						// 开始抽奖
						if(this.frequency >= 1){
							this.frequency--;
						}
						that.move();
						this.rNUm = 1; //记录轮询次数
						that.getStataus(info.data.key);
					}
				}).catch(error => {
					console.log(error)
				})
				// 请求接口，模拟一个抽奖数据(假设请求时间为2s)
				/*setTimeout(() => {
					this.award = {
						id: "10223"
					};
					console.log("返回的抽奖结果是", this.award);
				}, 2000);
				this.move();*/
			},
			getStataus(key) {
				let that = this;
				this.rNUm++;
				if (this.rNUm > 20) {
					uni.showToast({
						title: '谢谢参与',
						icon: 'none',
						duration:3000
					})
					this.isRuningLucky = false;
					return false;
				}

				this.$request({
					url: that.$api.luckyDraw.awardStatus,
					method: 'get',
					data: {
						activityid: that.activityId,
						key: key,
					},
				}).then(info => {
					console.log(info);
					//错误信息
					if (info.code == 203) {
						uni.showToast({
							title: info.msg,
							icon: 'none',
							duration: 3000
						})
						this.isRuningLucky = false;
						return false;
					} else if (info.code == 204) {
						//未关注
						this.isRuningLucky = false;
						this.followQrcode = info.data.url;
						this.showFollow = true;
						return false;
					} else if (info.code == 206) {
						//活动未实名认证
						this.isRuningLucky = false;
						this.showVerify = true;
						this.verifyUrl = info.data.url;
						return false;
					} else if (info.code == 207 || info.code == 208) {
						//活动未开始或已结束
						this.isRuningLucky = false;
						this.activityLabel = true;
						this.activityDesc = info.data.title;
						this.activityTitle = info.data.desc;
						return false;
					} else if (info.code == 209) {
						setTimeout(() => {
							that.getStataus(key);
						}, 800);

						return;
					}

					var result = info.data;
					this.award = {
						id: result.prizeid
					};


				}).catch(error => {
					console.log(error)
				})
			},
			move() {
				let timer = setTimeout(() => {
					this.current = this.rule.shift();
					this.rule.push(this.current);
					// 若抽中的奖品id存在，则开始减速转动
					if (this.award.id && (Date.now() - this.time) / 1000 > 2) {
						console.log("奖品出来了");
						this.speed += this.diff; // 转动减速
						// 若转动时间超过4秒，并且奖品id等于小格子的奖品id，则停下来
						if ((Date.now() - this.time) / 1000 > 6 && this.award.id == this.awards[this.current].id) {
							clearTimeout(timer);
							setTimeout(() => {
								this.isRuningLucky = false;
								// 这里写停下来要执行的操作（弹出奖品框
								this.showPopup(this.awards[this.current].name, this.awards[this.current].image_url, this.awards[this.current]
									.type);
								//Toast("您抽中的奖品是" + this.awards[this.current].name + ",奖品id是" + this.awards[this.current].id);
							}, 400);
							return;
						}
						// 若抽中的奖品不存在，则加速转动
					} else {
						if (this.speed >= 50) {
							this.speed -= this.diff; // 转动加速
						}
					}

					this.move();
				}, this.speed);
			},
			// 中奖名单滚动
			scroll() {
				this.animate = true;
				let timer = setTimeout(() => {
					this.list.push(this.list[0]);
					this.list.shift();
					this.animate = false;
				}, 500);
			},
			addColumnClass: function(index) {
				return index == 2 || index == 5 || index == 8
			},
			addRowClass: function(index) {
				return index == 4 || index == 5 || index == 6
			},
			initAwards: function(dataInput) {
				let data = dataInput;
				let arr = [];
				arr[0] = data[0];
				arr[1] = data[1];
				arr[2] = data[2];
				arr[5] = data[3];
				arr[4] = {
					id: 0,
					name: '',
					image_url: ''
				};
				arr[8] = data[4];
				arr[7] = data[5];
				arr[6] = data[6];
				arr[3] = data[7];
				this.awards = arr;
			},
			register() {
				this.show = false;
			},
			hotProduct() {
				this.show = false;
			},
			getItNow() {
				this.show = false;
			},
			myPrize() {
				var that = this;
				//跳转到我的奖品页面
				uni.navigateTo({
					url: '/pages/myPrize/myPrize?activityId='+that.activityId
				});
			}
		}
	};
</script>
<style lang="scss" scoped>
	.kugou-content {
		width: 100%;
		background-color: #ffd7b3;
		position: relative;

		// 顶部图片
		.bg-banner {
			width: 100%;

		}

		.nav {
			width: 130rpx;
			height: 100rpx;
			top: 55rpx;
			position: absolute;
		}

		.left {
			left: 0;
		}

		.right {
			right: 0;
		}

		// 滚动号码
		.kugou-scroll {
			padding: 100rpx;
			position: absolute;
			top: 350rpx;
			width: 100%;

			.bg-scroll {
				background-color: #000000;
				opacity: 0.5;
				color: #ffffff;
				border-radius: 16rpx;
				width: 100%;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 30rpx;
				overflow: hidden;
				text-align: center;
				letter-spacing: 3rpx;
			}

			.lkq-name {
				margin: 0 auto;
				color: #fff;
				font-size: 20rpx;
			}

			.anim {
				transition: all 0.5s linear;
				margin-top: -59rpx;
			}
		}

		.opportunity {
			width: 100%;
			height: 15rpx;
			line-height: 15rpx;
			top: 560rpx;
			padding: 0 30rpx;
			position: absolute;
			color: #ffffff;
			font-size: 25rpx;
			text-align: center;
			z-index: 3;

			span {
				color: #fbe108;
			}
		}

		// 抽奖
		.turntable {
			.present-content {
				width: 100%;
				height: 53%;
				position: absolute;
				top: 500rpx;
				z-index: 1;
				background: center top no-repeat;
				background-size: 100%, 100%;

				.present {
					width: 79%;
					height: 79%;
					position: absolute;
					top: 110rpx;
					left: 89rpx;
					z-index: 1;

					.present-item {
						width: 192rpx;
						height: 180rpx;
						z-index: 2;
						float: left;
						border-radius: 15rpx;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;

						.present-item-name {
							font-size: 20rpx;
							text-align: center;
							color: #dc543c;
						}

						.prize {
							width: 100rpx;
							height: 100rpx;
						}
					}

					.in-column-center {
						margin-left: -7rpx;
						margin-right: -7rpx;
					}

					.in-row-center {
						margin-top: -12rpx;
						margin-bottom: -20rpx;
					}

					.current {
						//width: 150rpx;
						//height: 150rpx;

						background-color: #ffe400;
						background: url("../../static/images/getAwardFlash.png") center top no-repeat;
						background-size: 100%, 100%;
					}

					.middle {}
				}
			}

			.start-btn-big {
				width: 190rpx;
				position: absolute;
				top: 774rpx;
				left: 279rpx;
				z-index: 1;
				animation: btn-animation 0.5s ease-out infinite alternate;
			}

			.disable-start-btn-big {
				width: 1.8rpx;
				position: absolute;
				top: 3.1rpx;
				left: 2.88rpx;
				z-index: 2;
			}

			.call-friend {
				position: absolute;
				bottom: -10rpx;
				left: 160rpx;
				width: 400rpx;
				height: 100rpx;
			}
			
			.paticipate-people{
				position: absolute;
				bottom: 30rpx;
				left: 180rpx;
				width: 400rpx;
				height: 100rpx;
				text-align: center;
				color: #ffffff;
			}

			.run-item-0 {
				width: 100rpx;
			}

			.run-item-1 {
				width: 2.03rpx;
				display: block;
				margin: 0 0 0 1.93rpx;
			}

			.run-item-2 {
				width: 2.03rpx;
				display: block;
				margin: 0 0 0 3.85rpx;
			}

			.run-item-3 {
				width: 2.03rpx;
				display: block;
				margin: 1.9rpx 0 0 3.85rpx;
			}

			.run-item-4 {
				width: 2.03rpx;
				display: block;
				margin: 3.8rpx 0 0 3.85rpx;
			}

			.run-item-5 {
				width: 2.03rpx;
				display: block;
				margin: 3.8rpx 0 0 1.925rpx;
			}

			.run-item-6 {
				width: 2.03rpx;
				display: block;
				margin: 3.8rpx 0 0 0;
			}

			.run-item-7 {
				width: 2.03rpx;
				display: block;
				margin: 1.9rpx 0 0 0;
			}
		}

	}

	@keyframes btn-animation {
		0% {
			transform: scale(1);
		}

		100% {
			transform: scale(0.85);
		}
	}

	.notice-img {
		position: absolute;
		top: 110rpx;
		left: 110rpx;
		width: 30rpx;
		height: 30rpx;
	}
</style>
